import React, { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';

export default function Message() {
  const { user } = useAuth();
  const [toId, setToId] = useState('');
  const [content, setContent] = useState('');
  const [messages, setMessages] = useState([]);
  const [friends, setFriends] = useState([]);

  useEffect(() => {
    if (user) {
      fetch(`/api/friend/${user.student_id}`)
        .then(res => res.json())
        .then(data => setFriends(data.data || []));
    }
  }, [user]);

  useEffect(() => {
    if (user && toId) fetchMessages(user.student_id, toId);
  }, [user, toId]);

  const fetchMessages = async (sid, fid) => {
    if (!sid || !fid) return;
    const res = await fetch(`/api/message/${sid}/${fid}`);
    const data = await res.json();
    if (data.success) setMessages(data.data);
  };

  const handleSend = async (e) => {
    e.preventDefault();
    if (!user || !toId || !content) {
      alert('请填写完整信息');
      return;
    }
    const res = await fetch('/api/message', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ from_id: user.student_id, to_id: toId, content })
    });
    const data = await res.json();
    if (data.success) {
      setContent('');
      fetchMessages(user.student_id, toId);
    } else {
      alert(data.message || '发送失败');
    }
  };

  return (
    <div className="card">
      <h2>好友消息</h2>
      <div style={{ display: 'flex', gap: 24 }}>
        <div style={{ minWidth: 160 }}>
          <h3 style={{ fontSize: 16 }}>我的好友</h3>
          <ul style={{ listStyle: 'none', padding: 0 }}>
            {friends.length === 0 && <li style={{ color: '#888' }}>暂无好友</li>}
            {friends.map(f => (
              <li key={f.friend_id} style={{ marginBottom: 8 }}>
                <button
                  style={{ background: toId === f.friend_id ? '#1976d2' : '#f0f4f8', color: toId === f.friend_id ? '#fff' : '#1976d2', border: 'none', borderRadius: 6, padding: '6px 12px', cursor: 'pointer', width: '100%' }}
                  onClick={() => setToId(f.friend_id)}
                >
                  {f.name}（{f.friend_id}）
                </button>
              </li>
            ))}
          </ul>
        </div>
        <div style={{ flex: 1 }}>
          <form onSubmit={handleSend} style={{ marginBottom: 20, display: 'flex', gap: 12 }}>
            <input type="text" placeholder="消息内容" value={content} onChange={e => setContent(e.target.value)} style={{ width: 300 }} disabled={!toId} />
            <button type="submit" disabled={!toId}>发送</button>
          </form>
          <h3>消息记录</h3>
          <div style={{ border: '1px solid #eee', padding: 10, minHeight: 100, background: '#f9f9f9', borderRadius: 6 }}>
            {toId ? (
              messages.length === 0 ? <div style={{ color: '#888' }}>暂无消息</div> :
                messages.map(m => (
                  <div key={m.message_id} style={{ marginBottom: 8, color: m.from_id === (user && user.student_id) ? '#1976d2' : '#388e3c' }}>
                    <b>{m.from_id === (user && user.student_id) ? '我' : '对方'}：</b>{m.content} <span style={{ fontSize: 12, color: '#888' }}>{new Date(m.send_time).toLocaleString()}</span>
                  </div>
                ))
            ) : <div style={{ color: '#888' }}>请选择好友</div>}
          </div>
        </div>
      </div>
    </div>
  );
} 